#include "iothread.h"

uvNameSpaceBegin


static void do_work(void* arg) {

	ptrnull_return(arg);
	io_thread_t* p = (io_thread_t*)(arg);
	p->runfunction(p);
}
static void event_iothread_cb(int istart, void *pdata) {

	ptrnull_return(pdata);
	io_thread_t* p = (io_thread_t*)(pdata);

	os_thread_t pThread = os_thread_self();
	p->tid = os_getthread_id(&pThread);

	if (istart) {
		p->startfunction(p->data);
	}
	else {
		p->stopfunction(p->data);
	}
}
int	thread_init(io_thread_t* pThis, void* pdata,
	async_fun_cb startcb, async_fun_cb runcb, async_fun_cb stopcb) {

	ptrnull_value(pThis, IO_VALUE_ERROR)
	pThis->data = pdata;
	pThis->startfunction = startcb;
	pThis->runfunction = runcb;
	pThis->stopfunction = stopcb;
	pThis->tid = 0;
	pThis->eventloop = (io_event_loop*)malloc(sizeof(io_event_loop));
	return create_ioeventloop(pThis->eventloop, event_iothread_cb, pThis);
}
int	thread_start(io_thread_t* pThis) {

	ptrnull_value(pThis, IO_VALUE_ERROR)
	return os_thread_create(&pThis->threadhandler, do_work, pThis);
}
int	thread_stop(io_thread_t* pThis) {

	ptrnull_value(pThis, IO_VALUE_ERROR)
	destory_ioeventloop(pThis->eventloop);
	return os_thread_join(&pThis->threadhandler);
}
uvNameSpaceEnd
